# Function to obtain the AMCE as in Table 4
amce_compute_abstain <- function(vote.mat, pos, value.baseline, value.amce, weights = NULL, idvar) {
  df <- vote.mat
  n.atts <- nchar(df$C1[1])
  
  df$name1 <- paste0(df$C1, "-", df$C2)
  df$name2 <- paste0(df$C2, "-", df$C1)
  
  # generate all possible comparisons
  combs <- data.frame(C1 = unique(c(df$C1, df$C2)))
  combs$C1 <- as.character(combs$C1)
  both.combs <- data.frame(permutations(n = length(combs$C1), r = 2, v = combs$C1, repeats.allowed = TRUE))
  
  # restrict to value of interest
  comp1 <- both.combs[substr(both.combs$X1, pos, pos)==value.amce,]
  names(comp1) <- c("C1", "C2")
  comp1$name1 <- paste0(comp1$C1, "-", comp1$C2)
  comp1$name2 <- paste0(comp1$C2, "-", comp1$C1)
  
  # flip to baseline
  comp2 <- comp1
  comp2$C1 <- paste0(substr(comp1$C1, 0, pos-1), value.baseline, substr(comp1$C1, pos + 1,
                                                                        nchar(as.character(comp1$C1))))
  comp2$name1 <- paste0(comp2$C1, "-", comp2$C2)
  comp2$name2 <- paste0(comp2$C2, "-", comp2$C1)
  
  # compute individual AMCEs
  df1 <- df[,!names(df) %in% "name1"]
  df2 <- df[,!names(df) %in% "name2"]
  names(df1)[ncol(df1)] <- names(df2)[ncol(df2)] <- "name"
  df_all <- rbind(df1, df2)
  amce.ind <- data.frame(voter = unique(df[,idvar]), amce = NA)
  for (i in 1:nrow(amce.ind)) {
    # compute whether C1 wins for every combination
    tomerge <- df_all[df_all[,idvar]==i, c("name", "choice")]
    winstats <- merge(comp1, tomerge[!duplicated(tomerge),], by.x = "name1", by.y = "name", all.x = TRUE)
    win.c1 <- ifelse(winstats$C1==winstats$C2 & !is.na(winstats$choice), .5, ifelse(winstats$choice==winstats$C1 & !is.na(winstats$choice), 1, 0))
    names(win.c1) <- winstats$name1
    # flip and compute
    winstats <- merge(comp2, tomerge[!duplicated(tomerge),], by.x = "name1", by.y = "name", all.x = TRUE)
    win.cf <- ifelse(winstats$C1==winstats$C2 & !is.na(winstats$choice), .5, ifelse(winstats$choice==winstats$C1 & !is.na(winstats$choice), 1, 0))
    names(win.cf) <- winstats$name1
    # compute individual amce
    amce.ind$amce[i] <- sum(win.c1 - win.cf)
  }
  
  # normalize all
  norm <- ((2^n.atts)) * (2^(n.atts - 1))
  amce.ind$amce <- amce.ind$amce/norm
  
  # compute mean of the difference between the two
  if (is.null(weights)) {
    amce <- mean(amce.ind$amce)
  } else {
    amce <- weighted.mean(amce.ind$amce, weights)
  }
  
  return(list(amce = amce, amce.ind = amce.ind))
}